<template>
  <div class="entering">
    <el-card class="box-card">
      <!-- 头部 -->
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '试题修改' : '试题录入'}}</span>
      </div>
      <!-- 表单区域 -->
      <el-form :model="questionInfo" :rules="rules" ref="questtionForm">
        <el-form-item label="学科:" prop="subjectID" label-width="100px">
          <el-select v-model="questionInfo.subjectID" placeholder="请选择" @change="subjectChangeFn">
            <el-option
              v-for="subject in questionData.subjectList"
              :label="subject.label"
              :value="subject.value"
              :key="subject.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID" label-width="100px">
          <el-select v-model="questionInfo.catalogID" :placeholder="questionInfo.subjectID ? '请选择' : '请先选择学科'">
            <el-option
              v-for="dir in questionData.directoryList"
              :key="dir.value"
              :label="dir.label"
              :value="dir.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID" label-width="100px">
          <el-select v-model="questionInfo.enterpriseID" placeholder="请选择">
            <el-option
              v-for="comp in questionData.companyList"
              :key="comp.id"
              :label="comp.company"
              :value="comp.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="city" label="城市:" prop="city" label-width="100px">
          <el-select @change="provinceChangeFn" v-model="questionInfo.province" placeholder="请选择">
            <el-option
              v-for="(prov,i) in questionData.provincesList"
              :key="i"
              :label="prov"
              :value="prov"></el-option>
          </el-select>
           <el-select v-model="questionInfo.city" prop="region" :placeholder="questionInfo.province ? '请选择' : '请先选择一级城市'" label-width="100px" >
            <el-option
              v-for="(city,i) in questionData.citys"
              :key="i"
              :label="city"
              :value="city"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向:" prop="direction" label-width="100px">
          <el-select v-model="questionInfo.direction" placeholder="请选择" label-width="100px">
            <el-option
              v-for="(direction, i) in questionData.direction"
              :key="i"
              :label="direction"
              :value="direction"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" label-width="100px">
          <el-radio-group v-model="questionInfo.questionType" @change="questionTypeChangeFn">
            <el-radio
              v-for="item in questionData.questionType"
              :key="item.value"
              :label="String(item.value)">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" label-width="100px">
          <el-radio-group v-model="questionInfo.difficulty">
            <el-radio
              v-for="item in questionData.difficulty"
              :key="item.value"
              :label="String(item.value)">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question" label-width="100px">
           <quill-editor
            ref="questionStem"
            v-model="questionInfo.question"
            :options="stemOptions"
            @blur="questionValidateFn"></quill-editor>
        </el-form-item>

        <el-form-item v-if="questionInfo.questionType === '1'" label="选项:" label-width="100px">
          <div class="radioGroup">
            <el-radio-group @change="radioGroupChangeFn" v-model="optionCode">
            <div class="opt" v-for="(opt,i) in questionData.optionsCountList" :key="i">
              <el-radio :label="opt.code" > {{ opt.code + ':' }} </el-radio>
              <el-input v-model="opt.title" @input="radioGroupChangeFn"></el-input>
            <div class="pic">
            </div>

            </div>
          </el-radio-group>
          </div>
          <div class="btnm">
            <el-button type="danger" disabled size="small">+增加选项与答案</el-button>
          </div>
        </el-form-item>

        <el-form-item v-if="questionInfo.questionType === '2'" label="选项:" label-width="100px">
          <div class="radioGroup">
            <el-checkbox-group @change="checkboxGroupChangeFn" v-model="checkList">
              <div class="opt" v-for="(opt,i) in questionData.optionsCountList"   :key="i">
                <el-checkbox :label="opt.code"> {{ opt.code + ':' }} </el-checkbox>
                <el-input v-model="opt.title" @input="checkboxGroupChangeFn"></el-input>
              </div>
            </el-checkbox-group>
          </div>
          <div class="btnm">
            <el-button type="danger" size="small" @click="addChenckBoxFn">+增加选项与答案</el-button>
          </div>
        </el-form-item>
        <el-form-item label="解析视频:" prop="videoURL" label-width="100px">
          <el-input v-model="questionInfo.videoURL"></el-input>
        </el-form-item>

        <el-form-item label="答案解析:" prop="answer" label-width="100px">
           <quill-editor
            ref="answerParse"
            v-model="questionInfo.answer"
            :options="stemOptions"
            @blur="answerValidateFn"></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注:" prop="remarks" label-width="100px">
           <el-input type="textarea" v-model="questionInfo.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签:" prop="tags" label-width="100px">
           <el-select
              v-model="tagArr"
              @change="tagChangeFn"
              multiple
              filterable
              allow-create
              :placeholder="questionInfo.subjectID ? '请选择试题标签' : '请先选择学科'">
             <el-option
              v-for="(tag,i) in questionData.tagList"
              :key="i"
              :label="tag.label"
              :value="tag.label"></el-option>
           </el-select>
        </el-form-item>
        <el-form-item label-width="100px">
          <el-button :type="isEdit ? 'success' : 'primary'" @click="onSubmit">{{ isEdit ? '确认修改' : '确认提交'}}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 富文本修改器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

// 获取学科列表接口
import { simple as subjectList } from '@/api/hmmm/subjects.js'
// 目录列表接口
import { simple as directoryList } from '@/api/hmmm/directorys.js'
// 公司列表接口
import { list as companyList } from '@/api/hmmm/companys.js'
// 标签列表接口
import { simple as tagList } from '@/api/hmmm/tags.js'
// 基础题库添加接口, 详情, 修改
import { add, detail, update } from '@/api/hmmm/questions.js'

// 获取方向, 题型, 难度
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 获取所有城市
import { provinces, citys } from '@/api/hmmm/citys.js'
export default {
  name: 'questionsNew',
  data () {
    // 工具栏配置
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
      ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
      // [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
      [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
      // [{ script: 'sub' }, { script: 'super' }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
      // [{ indent: '-1' }, { indent: '+1' }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
      // [{ direction: 'rtl' }], // 文本方向-----[{'direction': 'rtl'}]
      // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
      // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
      // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
      // [{ font: [] }], // 字体种类-----[{ font: [] }]
      // [{ align: [] }], // 对齐方式-----[{ align: [] }]
      // ['clean'], // 清除文本格式-----['clean']
      ['image', 'link'] // 链接、图片、视频-----['link', 'image', 'video']
    ]

    // 自定义校验标签
    var validateTags = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请选择至少一个标签'))
      } else {
        callback()
      }
    }

    return {
      isEdit: false,
      // imageUrl: '', // 上传图片
      codeNum: 69, // 选项编码
      tagArr: [], // 标签数组
      optionCode: '', // 单选的值
      checkList: [], // 多选数组
      // 试题数据
      questionData: {
        subjectList: [], // 学科列表
        directoryList: [], // 当前学科目录列表
        companyList: [], // 公司列表
        provincesList: provinces(), // 城市列表
        citys, // 二级城市
        direction, // 方向
        questionType, // 题型
        difficulty, // 难度
        tagList: [], // 标签列表
        optionsCountList: [
          {
            code: 'A', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'B', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'C', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'D', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ]
      },
      // 所选试题信息
      questionInfo: {
        subjectID: '', // 所选学科 id
        catalogID: '', // 所选目录 id
        enterpriseID: '', // 所选公司 id
        province: '', // 所选城市
        city: '', // 所选二级城市
        direction: '', // 所选方向
        questionType: '1', // 所选题型
        difficulty: '1', // 所选难度
        tags: '', // 所选标签
        question: '', // 题干内容
        videoURL: '', // 解析视频地址
        answer: '', // 答案解析
        remarks: '', // 题目备注
        // 选项
        options: []

      },
      // 表单验证
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [
          { validator: validateTags, trigger: 'blur' }
        ],
        videoURL: [
          { required: true, message: '请输入解析视频地址', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请输入题目备注', trigger: 'blur' }
        ]
      },
      currentTabComponent: '',
      // 题干富文本配置
      stemOptions: {
        modules: {
          // 工具栏
          toolbar: toolbarOptions
        },
        placeholder: ''
      },
      stemOptions2: {
        modules: {
          // 工具栏
          toolbar: toolbarOptions
        },
        placeholder: ''
      }
    }
  },
  components: {
    quillEditor
  },
  async created () {
    // 获取学科列表
    this.getSubjectsListFn()
    // 获取公司列表
    this.getcompanysListFn()
    console.log(questionType)
    // 初始化选项数据
    this.questionInfo.options = this.questionData.optionsCountList

    console.log(this.$route.query.id)
    // 调用试题修改
    this.$route.query.id && this.updateQuestionFn()
  },
  methods: {
    // 提交按钮
    onSubmit () {
      this.$refs.questtionForm.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            const updateRes = await update(this.questionInfo)
            console.log(updateRes)
            updateRes.data.success ? this.$message.success('修改成功') : this.$message.success('修改失败')
          } else {
            const res = await add(this.questionInfo)
            console.log(res)
            this.$message.success('提交成功')
          }
          this.$router.push('/questions/list')
        } else {
          this.$message.error('提交失败, 请完成校验')
        }
      })
    },

    // 题型改变
    questionTypeChangeFn () {
      this.optionCode = '' // 单选的值
      this.checkList = [] // 多选数组
    },

    // 试题修改
    async updateQuestionFn () {
      this.isEdit = true
      const res = await detail({ id: this.$route.query.id })
      console.log(res)
      this.questionInfo = res.data
      // 标签赋值
      this.tagArr = this.questionInfo.tags.split(',')
      // 将数据赋值给遍历数据
      this.questionData.optionsCountList = this.questionInfo.options
      // 判断是否为单选
      if (this.questionInfo.questionType === '1') {
        return this.questionInfo.options.forEach(item => {
          if (item.isRight === 1) {
            this.optionCode = item.code
          }
        })
      }
      if (this.questionInfo.questionType === '2') {
        return this.questionInfo.options.forEach(item => {
          if (item.isRight === 1) {
            this.checkList.push(item.code)
          }
        })
      }
    },

    // 题干校验
    questionValidateFn () {
      this.$refs.questtionForm.validateField('question')
    },
    // 答案解析校验
    answerValidateFn () {
      this.$refs.questtionForm.validateField('answer')
    },

    // 多选添加选项按钮
    addChenckBoxFn () {
      console.log(this.codeNum)
      if (this.codeNum > 90) return this.$message('已达到最大选项数')
      this.questionData.optionsCountList.push({
        code: String.fromCharCode(this.codeNum), // ASCII码转换字母
        title: '', // 标题
        img: '', // 图片URL
        isRight: 'false' // 是否正确答案
      })
      this.codeNum += 1
    },

    // 单选选项改变
    radioGroupChangeFn (value) {
      const radioData = this.questionData.optionsCountList.map(item => {
        if (value === item.code) {
          return {
            ...item,
            isRight: true
          }
        } else {
          return {
            ...item,
            isRight: false
          }
        }
      })
      this.questionInfo.options = radioData
    },

    // 多选改变
    checkboxGroupChangeFn (value) {
      console.log(value)
      const checkboxData = this.questionData.optionsCountList.map(item => {
        if (value.includes(item.code)) {
          return {
            ...item,
            isRight: true
          }
        }
        return {
          ...item,
          isRight: false
        }
      })
      this.questionInfo.options = checkboxData
    },

    // 获取学科列表
    async getSubjectsListFn () {
      const res = await subjectList()
      console.log(res)
      this.questionData.subjectList = res.data
    },
    // 获取目录列表
    async getdirectorysListFn () {
      const res = await directoryList({ subjectID: this.questionInfo.subjectID })
      console.log(res)
      this.questionData.directoryList = res.data
    },

    // 获取公司列表
    async getcompanysListFn () {
      // 默认每页 10 个公司, 而公司总数大于 10, 需要将数据全部请求回来
      const res = await companyList({ pagesize: 20 })
      console.log(res)
      this.questionData.companyList = res.data.items
    },

    // 获取标签列表
    async getTagsList () {
      const res = await tagList({ subjectID: this.questionInfo.subjectID, pagesize: 20 })
      console.log(res)
      this.questionData.tagList = res.data
    },

    // 学科改变时
    subjectChangeFn () {
      // 获取当前学科目录
      this.getdirectorysListFn()
      // 获取标签
      this.getTagsList()
    },

    // 城市改变
    provinceChangeFn () {
      console.log(this.questionInfo.province)
      this.questionData.citys = citys(this.questionInfo.province)
      console.log(citys('北京市'))
    },

    // 标签改变
    tagChangeFn () {
      this.questionInfo.tags = this.tagArr.join()
    }
  },
  watch: {
    // 'questionInfo.questionType': function () {
    //   console.log('监听到了变化')
    //   // 监听选项类型变化, 更改所有 isRight 选项为 false
    //   this.questionInfo.options.forEach(item => { this.$set(item, 'isRight', false) })
    //   // 题型改变时, 重置所有选项
    //   this.checkList = []
    //   this.optionCode = ''
    // },
    'questionData.optionsCountList': {
      handler: function () {
        this.questionInfo.options = this.questionData.optionsCountList
      },
      deep: true
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.entering {
  padding: 20px 20px;

  &::v-deep .el-input__inner {
    width: 400px
  }
}
.city ::v-deep .el-input__inner {
  width: 200px
}

// 单选选项
.opt {
  display: flex;
  align-items: center;
  padding-bottom: 30px;

  .el-input--medium {
    width: 400px;
  }
  .el-radio {
    text-indent: 2px;
  }

  .el-checkbox {
    text-indent: 2px;
    padding-right: 30px;
  }

  .pic {
    // background: chocolate;
    width: 100px;
    height: 50px;

    &::v-deep .el-upload--picture-card  {
      width: 100px;
      height: 50px;
    }
  }
}

 .quill-editor ::v-deep .ql-container {
 height: 200px
}
</style>
